package view.Validator;

import javafx.scene.control.Control;
import javafx.scene.control.TextField;

import org.controlsfx.validation.ValidationResult;
import org.controlsfx.validation.Validator;

/**
 * 
 * Provides a <code>Validator</code> that checks the range of a given integer input.
 * In order to use this Validator one of the factory methods must be invoked.
 * 
 * @version %I%, %G%
 */
public class IntegerNumberRangeValidator implements Validator<String>{

	private int	min;
	private int	max;

	private IntegerNumberRangeValidator(int min, int max) {

		this.min = min;
		this.max = max;
	}

	public static IntegerNumberRangeValidator createNumberRangeValidator(int min, int max) {

		return new IntegerNumberRangeValidator(min, max);
	}

	public static IntegerNumberRangeValidator createMinNumberRangeValidator(int min) {

		return new IntegerNumberRangeValidator(min, Integer.MAX_VALUE);
	}

	public static IntegerNumberRangeValidator createMaxNumberRangeValidator(int max) {

		return new IntegerNumberRangeValidator(Integer.MIN_VALUE, max);
	}

	@Override
	public ValidationResult apply(Control t, String u) {

		ValidationResult res = new ValidationResult();
		final String MSGRANGE = "Es muss eine Zahl zwischen " + min + " und " + max
				+ " eingegeben werden.\nEs duerfen nur ganze Zahlen eingegeben werden.";
		if (t instanceof TextField) {
			try {
				if (((TextField) t).getText().equals("")) {
					return res;
				}
				int input = Integer.valueOf(((TextField) t).getText());
				boolean isInRange = input >= min && input <= max;
				if (!isInRange) {
					res.addErrorIf(t, MSGRANGE, true);
				} else if (input == 0) {
					res.addWarningIf(t, "Achtung moeglicherweise falsche Eingabe.", true);
				}
			} catch (NumberFormatException e) {
				res.addErrorIf(t, MSGRANGE, true);
			}
		}
		return res;
	}
}
